import config from '@/admin.config.js';
import ToolRouter from '@/tool/http/ToolRouter.js';
import ToolUni from "@/tool/ToolUni.js";
import ToolUrl from '@/tool/http/ToolUrl';

let storeMenu = {
	namespaced: true,
	state: {
		menus: [...config.sideBar.staticMenu],
		staticMenu: config.sideBar.staticMenu,
		dynamicMenu: [],
		userMenu: [],
		selectMenu: {
			children: []
		},
		selectChildrenList: []
	},
	mutations: {
		updateSelectMenu(state, selectMenu) {
			if (!selectMenu) {
				let currentUrl = ToolUni.getCurrentUrl();
				selectMenu = state.menus.find(item => currentUrl === item.value);
				if (!selectMenu) {
					selectMenu = state.menus.find(item => "/" === item.value);
				}
			}
			if (!selectMenu) {
				return;
			}
			state.menus.forEach(item => item.active = false);

			let pMenu = selectMenu;

			if (selectMenu.parent_id) {
				pMenu = state.menus.find(item => item.menu_id === selectMenu.parent_id);
			}
			pMenu.active = true;
			selectMenu.active = true;

			state.selectMenu = pMenu;
			state.selectChildrenList = state.menus.filter(item => item.parent_id === pMenu.menu_id);

			if (pMenu === selectMenu && state.selectChildrenList.length > 0) {
				state.selectChildrenList[0].active = true
			}
		},
		updateDynamicMenu(state, dynamicMenus) {
			state.dynamicMenu = dynamicMenus;
			state.menus = [...config.sideBar.staticMenu, ...state.userMenu, ...state.dynamicMenu];
		},
		updateUserMenus(state, userMenus) {
			state.userMenu = userMenus;
			state.menus = [...config.sideBar.staticMenu, ...state.userMenu, ...state.dynamicMenu];
		},
		updateMenus(state, menus) {
			state.menus = menus;
		}
	},
	actions: {
		async initMenus(context) {
			if (context.rootState.login.token) {
				let menus = uni.getStorageSync("n-menus");
				if (menus) {
					context.commit("updateMenus", menus);
				} else {
					context.commit("updateDynamicMenu", await ToolRouter.menus());
					// context.commit("updateUserMenus", await initUserMenus());
					ToolUni.storage("n-menus", context.state.menus);
				}
			}
			context.commit("updateSelectMenu");
		},
		async refreshMenu(context) {
			ToolUni.storage("n-menus", null);
			await context.dispatch("initMenus");
		},
		updateCurrentMenu(context, val) {
			context.commit("updateSelectMenu", val);
			ToolUni.toPage((context.state.selectChildrenList[0] || val).value);
		}
	}
}

// async function initUserMenus() {
// 	let res = await uniCloud.database().collection('opendb-admin-menus')
// 		.field("url as value, name as text, menu_id, parent_id, sort, icon, permission")
// 		.orderBy("sort asc")
// 		.get();
// 	return res.result.data;
// }

export default storeMenu;
